package Lee_code;

/**
 * @author blh
 * @date 2024年07月15日 8:56
 */
public class Lee_59_715 {
    public int[][] generateMatrix(int n) {
        int[][] matrix = new int[n][n];
        int r = n - 1, l = 0, up = 0, down = n - 1;
        int start = 1;
        while (true) {
            // 从左到右
            for (int i = l; i <= r; i++) {
                matrix[up][i] = start++;
            }
            up++;

            // 从上到下
            for (int i = up; i <= down; i++) {
                matrix[i][r] = start++;
            }
            r--;

            // 从右到左
            for (int i = r; i >= l; i--) {
                matrix[down][i] = start++;
            }
            down++;

            // 从下到上
            for (int i = down; i <= up; i++) {
                matrix[i][r] = start++;
            }
            l++;

            if (up > down || r > l) {
                break;
            }
        }
        return matrix;
    }
}
